<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\hgapi\controller;
use app\hgapi\model\activity\ActivityClock;
use app\hgapi\model\activity\ActivityList;
use app\hgapi\model\market\MarketBack;
use app\hgapi\model\store\StoreCategory;
use app\hgapi\model\store\StoreProductCoupon;
use app\hgapi\model\store\StoreProductEvaluate;
use app\hgapi\model\store\StoreProductEvaluateImg;
use app\hgapi\model\store\StoreProductImg;
use app\hgapi\model\store\StoreProduct;
use app\hgapi\model\store\StoreOrder;
use app\hgapi\model\store\StoreOrderList;
use app\hgapi\model\store\StoreRefund;
use app\hgapi\model\system\Site;
use app\hgapi\model\user\UserCart;
use app\hgapi\model\user\UserCoupon;
use app\hgapi\model\user\User;

class ProductApi extends Auth{

    /**
     * 获取所有商品分类并显示十条数据
     */
    public function get_category(){
        $start = input('start');
        $limit = input('limit');
        //查询分类并合并
        $category = StoreCategory::selCategoryInfo(['pid' => 0], ['status' => 1]); //上级
        $zi = StoreCategory::selCategoryInfo(['pid' => ['neq', 0]], ['status' => 1]); //二级类
        if($category) $category = $category->toArray();
        if($zi) $zi = $zi->toArray();
        foreach ($category as $k => $v){
            foreach ($zi as $key => $val){
                if ($val['pid'] == $v['id']){
                    $category[$k]['lower'][] = $zi[$key];
                }
            }
        }
        $arr = [['id' => 0, 'name' => '全部']];
        $category = array_merge($arr, $category);
        //查询商品
        $field = 'id,name,price';
        $data = StoreProduct::selProductLimit(['status' => 0, 'type' => 0, 'is_del' => 0], $field, $start, $limit);
        foreach ($data as $k => $v){
            $data[$k]['img'] = StoreProductImg::getImg($v['id']);
        }
        successCode(['category' => $category, 'data' => $data]);
    }

    /**
     * 根据分类获取商品
     */
    public function get_shop(){
        $start = input('start');
        $limit = input('limit');
        $type = input('type');
        $sort = input('sort');
        //查询当前分类
        if ($type){
            //判断提交过来的分类有没有下级
            $all = StoreCategory::columnCategory(['pid' => $type], 'id');
            array_unshift($all, $type);
            $where['cid'] = ['in', $all];
        }
        //当前排序方式
        if ($sort == 0){
            $order = 'time desc';
            $order2 = 'time asc';
        }elseif ($sort == 1){
            $order = 'volume desc';
            $order2 = 'volume asc';
        }elseif ($sort == 2){
            $order = 'time desc';
            $order2 = 'time asc';
        }elseif ($sort == 3){
            $order = 'price asc';
            $order2 = 'price desc';
        }else{
            $order = 'time desc';
            $order2 = 'time asc';
        }
        //查询商品
        $field = 'id,name,price';
        $where['status'] = 0;
        $where['type'] = 0;
        $where['is_del'] = 0;
        $data = StoreProduct::selProductLimit($where, $field, $start, $limit, $order);
        //查询当前数据最后一条id
        $id = StoreProduct::valueId($where, $order2);
        foreach ($data as $k => $v){
            $data[$k]['img'] = StoreProductImg::getImg($v['id']);
            //判断是当前组的最后一条id的话
            if ($v['id'] == $id){
                $data[$k]['is'] = 1;
            }
        }
        successCode($data);
    }

    /**
     * 获取订单
     */
    public function get_order(){
        $uid = input('uid'); //用户id
        $lei = input('lei'); //订单类型
        $start = input('start'); //起始位置
        $limit = input('limit'); //每次查询条数
        if ($lei == 0){
            $where = ['uid' => $uid];
        }elseif ($lei == 1){
            $where = ['uid' => $uid, 'status' => 0];
        }elseif ($lei == 2){
            $where = ['uid' => $uid, 'status' => 1];
        }elseif ($lei == 3){
            $where = ['uid' => $uid, 'status' => 2];
        }elseif ($lei == 4){
            $where = ['uid' => $uid, 'status' => 3];
        }else{
            $where = ['uid' => $uid];
        }
        $field = 'id,order,time,money,status,freight,ling,benefit,type';
        $last = StoreOrder::valueId($where, 'time asc'); //最后一条数据id
        $data = StoreOrder::selOrder($where, $field, $start, $limit);
        foreach ($data as $k => $v){
            $lower = StoreOrderList::selOrderListZhi($v['id']);
            foreach ($lower as $key => $val){
                $lower[$key]['img'] = StoreProductImg::getImg($val['pid']);
                $lower[$key]['unit'] = $this->buling($val['unit']);
            }
            $data[$k]['lower'] = $lower;
            $data[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
            if ($v['status'] == 5){ //退款状态是否审核了
                $data[$k]['refund'] = StoreRefund::valueRefund(['oid' => $v['id']], 'status');
            }
        }
        successCode(['data' => $data, 'last' => $last]);
    }

    /**
     * 补零
     * @param $number
     * @return string
     */
    public function buling($number){
        return sprintf("%01.2f", $number);
    }

    /**
     * 删除订单
     */
    public function del_order(){
        $uid = input('uid'); //用户id
        $id = input('id'); //订单id
        $re = StoreOrder::delOrder(['id' => $id, 'uid' => $uid]);
        if ($re){
            StoreOrderList::delOrderList(['oid' => $id]);
            successCode('删除成功');
        }else{
            errorCode('删除失败');
        }
    }

    /**
     * 确认收货
     */
    public function collect(){
        $uid = input('uid'); //用户id
        $id = input('id'); //订单id
        $re = StoreOrder::upField(['id' => $id, 'uid' => $uid], 'status', 3);
        $find = StoreOrder::getOrder(['id' => $id, 'uid' => $uid], '');
        if ($re){
            if ($find['type'] == 5){
                $market = MarketBack::getBackInfo(['id' => $find['back_id']], 'status, back_cost');
                if ($market && $market['status'] == 1){
                    User::incField($uid, 'give', $market['back_cost']);
                }
            }
            successCode('收货成功');
        }else{
            errorCode('收货失败');
        }
    }

    /**
     * 获取所有商品信息
     */
    public function whole_shop(){
        $id = json_decode(input('id'), true); //商品id
        $group = input('group'); //商品所选组
        $num = input('num'); //商品数量
        $cid = input('cid'); //优惠券id
        $clock_id = input('clock_id'); //打卡活动id
        $uid = input('uid'); //打卡活动id
        $shop = [];
        $total_price = 0;
        $sum = 0;
        $freight = 0;
        $benefit = 0;
        //查出会员等级优惠
        $zhe = User::selUserZhe($uid);
        if ($clock_id){ //打卡活动id
            //查出活动
            $clock = ActivityClock::selClockZhi($clock_id);
            foreach ($clock as $k => $v){
                $clock[$k]['pimg'] = StoreProductImg::getImg($v['pid']);
            }
            $clock = $clock[0];
        }else{
            if (is_array($id)){ //如果是数组则是购物车提交
                $cart = UserCart::selCart(['id' => ['in', $id]], 'id desc');
                foreach ($cart as $k => $v){
                    $find = StoreProduct::getProductInfo(['id' => $v['pid']], 'id, name, price, value, ftype, freight');
                    $shop[$k]['img'] = StoreProductImg::getImg($find['id']);
                    if ($find['ftype'] == 1){
                        $freight += $find['freight'];
                    }
                    $value = json_decode($find['value'], true);
                    if ($value){
                        foreach ($value as $key => $val){
                            if ($val['group'] == $v['spec']){
                                $shop[$k]['id'] = $find['id'];
                                $shop[$k]['group'] = $val['group'];
                                $shop[$k]['price'] = $this->buling($val['price']);
                                $shop[$k]['num'] = $v['num'];
                                $shop[$k]['name'] = $find['name'];
                                $total_price += $val['price'] * $v['num']; //所有商品的价格
                                $sum += $v['num']; //总数
                            }
                        }
                    }else{
                        $shop[$k]['id'] = $find['id'];
                        $shop[$k]['price'] = $this->buling($find['price']);
                        $shop[$k]['num'] = $v['num'];
                        $shop[$k]['name'] = $find['name'];
                        $total_price += $find['price'] * $v['num']; //所有商品的价格
                        $sum += $v['num']; //总数
                    }
                    //查出第一个活动id
                    $huo = ActivityList::is_id($v['pid']); //根据商品id查出活动id
                    if ($huo) break;
                }
            }else{
                $find = StoreProduct::getProductInfo(['id' => $id], 'id, name, price, value, ftype, freight, is_open, offset');
                $huo = ActivityList::is_id($id); //根据商品id查出活动id
                $shop[0]['img'] = StoreProductImg::getImg($find['id']);
                if ($find['ftype'] == 1){
                    $freight += $find['freight'];
                }
                $value = json_decode($find['value'], true);
                if ($value){
                    foreach ($value as $k => $v){
                        if ($v['group'] == $group){
                            $shop[0]['id'] = $find['id'];
                            $shop[0]['group'] = $v['group'];
                            $shop[0]['price'] = $this->buling($v['price']);
                            $shop[0]['num'] = $num;
                            $shop[0]['name'] = $find['name'];
                            $shop[0]['is_open'] = $find['is_open'];
                            $shop[0]['offset'] = $find['offset'];
                            $total_price += $v['price'] * $num; //所有商品的价格
                            $sum += $num; //总数
                        }
                    }
                }else{
                    $shop[0]['id'] = $find['id'];
                    $shop[0]['price'] = $this->buling($find['price']);
                    $shop[0]['num'] = $num;
                    $shop[0]['name'] = $find['name'];
                    $shop[0]['is_open'] = $find['is_open'];
                    $shop[0]['offset'] = $find['offset'];
                    $total_price += $find['price'] * $num; //所有商品的价格
                    $sum += $num; //总数
                }
            }

            if ($cid){
                $time = time();
                $u_cou = UserCoupon::getUserCoupon(['id' => $cid]);
                $coupon = StoreProductCoupon::getCoupon(['id' => $u_cou['cid']], '');
                if ($coupon['term'] == '0'){ //0为指定开始结束时间
                    $valid = explode(' - ', $coupon['valid']);
                    $start = strtotime($valid[0]);
                    $end = strtotime($valid[1]);
                    //判断当前优惠券是否在指定时间使用
                    if ($time >= $start && $time <= $end && ($coupon['doorsill'] == '0' ? true : $total_price >= $coupon['full'] ? true : false)){
                        if ($coupon['form'] == 0){
                            //减去折扣金额
                            $newMoney = $total_price - $coupon['discount'] <= 0 ? 0.01 : $total_price - $coupon['discount'];
                        }else{
                            $newMoney = round($total_price * $coupon['discount'] / 10, 1);
                        }
                        $benefit = $total_price - $newMoney;
                    }
                }else{ //多少天内使用
                    if (($u_cou['time'] + $coupon['valid'] * 24 * 60 * 60) > $time && ($coupon['doorsill'] == '0' ? true : $total_price >= $coupon['full'] ? true : false)){ //在指定时间内
                        if ($coupon['form'] == 0){
                            //减去折扣金额
                            $newMoney = $total_price - $coupon['discount'] <= 0 ? 0.01 : $total_price - $coupon['discount'];
                        }else{
                            $newMoney = round($total_price * $coupon['discount'] / 10, 1);
                        }
                        $benefit = $total_price - $newMoney;
                    }
                }
            }
        }
        successCode(compact('shop', 'total_price', 'sum', 'freight', 'newMoney', 'benefit', 'clock', 'huo', 'zhe'));
    }

    /**
     * 删除订单
     */
    public function del_order2(){
        $uid = input('uid'); //用户id
        $id = input('id'); //订单id
        $re = StoreOrder::delOrder(['id' => $id, 'uid' => $uid]);
        if ($re){
            StoreOrderList::delOrderList(['oid' => $id]);
        }
    }

    /**
     * 验证卡密
     */
    public function yan_kalman(){
        $kalman = input('kalman');
        $shop = json_decode(input('shop'), true); //下单商品
        //卡密直接领取
        $kashop = StoreProduct::getProductInfo(['id' => $shop[0]['id']], '');
        if ($kalman && $kashop['is_open']){
            $ka = explode("\n", $kashop['kalman']);
            if (in_array($kalman, $ka)){
                if ($kashop['offset'] == 0){
                    $newMoney = $kashop['price'];
                }else{
                    $newMoney = $kashop['offset'];
                }
                successCode($newMoney);
            }else{
                errorCode('兑换码错误');
            }
        }else{
            errorCode('兑换码为空');
        }
    }

    /**
     * 获取打卡活动数据
     */
    public function get_clock(){
        //打卡活动
        $clock = ActivityClock::selClockShuJu();
        foreach ($clock as $k => $v){
            $clock[$k]['pimg'] = StoreProductImg::getImg($v['pid']);
        }
        successCode($clock);
    }

    /**
     * 获取活动
     */
    public function clock_info(){
        $id = input('id'); //活动id
        $uid = input('uid'); //用户id
        $clock = ActivityClock::getClockZhi($id);
        $pimg = StoreProductImg::columnImg($clock['pid']);
        $imgs = "uploads/clock/$uid-$id.png";
        if (!file_exists($imgs)){
            $access_token = access_token();
            $scene = "page:7,upper:$uid,page_id:$id";
            $img = createImg($access_token, $scene);
            file_put_contents("uploads/clock/$uid-$id.png", $img);
        }
        $user = User::getUserInfo(['id' => $uid], 'name, portrait');
        $user['name'] = base64_decode($user['name']);
        $find = StoreOrder::getOrder(['active_id' => $id, 'uid' => $uid, 'type' => 1, 'status' => ['neq', 0]], '');
        $clock['num'] = convert($clock['num'] + StoreOrder::countOrder(['active_id' => $clock['id'], 'type' => 1]), 10000, '万人', '人');
        successCode(['clock' => $clock, 'pimg' => $pimg, 'qr_code' => $imgs, 'user' => $user, 'find' => $find]);
    }

    /**
     * 加购物车
     */
    public function add_cart(){
        $uid = input('uid'); //用户id
        $id = input('id'); //产品id
        $group = input('group'); //所选参数组
        $num = input('num'); //数量
        //查出是否已经有相同的商品在购物车
        $find = UserCart::getCart(['uid' => $uid, 'pid' => $id, 'spec' => $group], '');
        if ($find){ //已存在直接增加数量
            $re = UserCart::incField(['id' => $find['id']], 'num', $num);
        }else{ //没有则增加一条记录
            $add = [
                'uid' => $uid,
                'pid' => $id,
                'spec' => $group,
                'num' => $num
            ];
            $re = UserCart::add($add);
        }
        if ($re){
            successCode('添加成功');
        }else{
            errorCode('添加失败');
        }
    }

    /**
     * 获取购物车信息
     */
    public function get_cart(){
        $id = input('id'); //用户id
        $field = 'c.*, p.name, p.price, p.value';
        $data = UserCart::selCartZhi($id, $field);
        if ($data) $data = $data->toArray();
        foreach ($data as $k => $v){
            $data[$k]['img'] = StoreProductImg::getImg($v['pid']);
            $data[$k]['freight'] = $v['ftype'] == 1 ? $v['freight'] : 0; //如果为统计邮费再计算费用
            //判断产品是否有选项
            if ($v['value'] && $v['value'] != 'null'){
                $value = json_decode($v['value'], true);
                foreach ($value as $key => $val){
                    if ($v['spec'] == $val['group']){ //查出购物车spce的选项值
                        $data[$k]['s_price'] = $this->buling($val['price']);
                    }
                }
            }else{
                $data[$k]['s_price'] = $this->buling($v['price']);
            }
        }
        successCode($data);
    }

    /**
     * 修改所有数量
     */
    public function cart_num(){
        $cart = new UserCart;
        $newcart = json_decode(input('newcart'), true); //所有数据
        $cart->saveAll($newcart);
    }

    /**
     * 从购物车删除
     */
    public function cart_del(){
        $id = input('id'); //购物车数据id
        $uid = input('uid'); //提交的用户id
        $result = UserCart::delCart(['uid' => $uid, 'id' => ['in', explode(',', $id)]]);
        if ($result){
            successCode('删除成功');
        }else{
            errorCode('删除失败');
        }
    }

    /**
     * 检查选中的数据中是否有下架或者删除的商品
     */
    public function is_cart(){
        $id = json_decode(input('id'), true); //所有选中的数据
        foreach ($id as $k) {
            //从购物车查出数据
            $find = UserCart::getCart(['id' => $k], '');
            $re = StoreProduct::getProductInfo(['id' => $find['pid']], '');
            if (!$re){ //如果有不存在的就跳出循环
                errorCode('部分商品已下架或被删除');
            }elseif ($re['status'] == 1){ //如果有下架的也跳出循环
                errorCode('部分商品已下架或被删除');
            }
        }
        successCode('成功');
    }

    /**
     * 获取商品信息
     */
    public function shop_info(){
        $id =input('id');
        $uid =input('uid');
        $shop = StoreProduct::getProductInfo(['id' => $id], '');
        $spec = json_decode($shop['spec'], true); //产品规格
        $can = [];
        foreach ($spec as $k => $v){
            foreach ($v as $key => $val){
                $can[$k]['spec'] = $key;
                $can[$k]['bei'] = $val['bei'];
                $can[$k]['value']['name'] = $val['name'];
                $can[$k]['value']['img'] = $val['img'];
            }
        }
        $shop['img'] = StoreProductImg::columnImg($id);
        $shop['can'] = $can;
        $shop['value'] = json_decode($shop['value'], true); //产品值
        $tel = Site::getField('tel');
        //评价
        $evaluate = StoreProductEvaluate::selEvaluate(['pid' => $id], 0);
        foreach ($evaluate as $k => $v){
            $evaluate[$k]['img'] = StoreProductEvaluateImg::selEvaluateImg(['eid' => $v['id']]);
        }
        //商品能使用的优惠券
        $newCoupon = [];
        //查出所有优惠券
        $coupon = StoreProductCoupon::selCoupon(['status' => 1]);
        foreach ($coupon as $k => $v){
            $valid = explode(' - ', $v['valid']);
            $start = strtotime($valid[0]);
            $end = strtotime($valid[1]);
            if ($v['term'] == 1 || ($v['term'] == 0 && time() > $start && time() < $end)){
                if ($v['apply'] == 0){
                    array_push($newCoupon, $coupon[$k]);
                }else if ($v['apply'] == 1){
                    if (in_array($id, explode(',', $v['shop']))){
                        array_push($newCoupon, $coupon[$k]);
                    }
                }
            }
        }
        $imgs = "uploads/shop/$uid-$id.png";
        if (!file_exists($imgs)){
            $access_token = access_token();
            $scene = "page:1,upper:$uid,page_id:$id";
            $img = createImg($access_token, $scene);
            file_put_contents("uploads/shop/$uid-$id.png", $img);
        }
        $user = User::getUserInfoZhi($uid);
        $user['name'] = base64_decode($user['name']);
        successCode(['shop' => $shop, 'tel' => $tel, 'evaluate' => $evaluate, 'coupon' => $newCoupon, 'qr_code' => $imgs, 'user' => $user]);
    }

    /**
     * 领取优惠券
     */
    public function coupon(){
        $id = input('id'); //优惠券id
        $uid = input('uid'); //用户id
        //查出优惠券
        $find = StoreProductCoupon::getCoupon(['id' => $id], 'total, limit, receive, status');
        $total = $find['total']; //发放总量 0不限
        $limit = $find['limit']; //每人限领 0为不限
        $receive = $find['receive']; //已领取数量
        $status = $find['status']; //优惠券当前状态 0失效
        if ($status == '0'){
            errorCode('该优惠券目前不可领取');
        }
        //查出我领取当前优惠券的数量
        $num = UserCoupon::countCoupon(['uid' => $uid, 'cid' => $id]);
        if ($limit != '0' && $limit = $num){
            errorCode('已经领过了,不要贪心哦');
        }
        //判断是否还剩余优惠券
        if ($total != '0' && $total == $receive){
            errorCode('该优惠券已经被领完了,下次早点来哦');
        }
        //正常领取
        $arr = [
            'uid' => $uid, //领取用户
            'cid' => $id, //优惠券id
            'time' => time(), //领取时间
            'status' => 0,
        ];
        $re = UserCoupon::add($arr);
        if ($re){
            //领取成功之后增加优惠券的领取数量
            StoreProductCoupon::incField(['id' => $id], 'receive', 1);
            successCode('领取成功');
        }else{
            errorCode('领取失败,请稍后重试');
        }
    }

    /**
     * 计算订单实付
     */
    public function getOrderShi(){
        $uid = input('uid');
        $oid = input('oid');
        $find = StoreOrder::getOrder(['id' => $oid, 'uid' => $uid], 'money, benefit');
        $price = bcsub($find['money'], $find['benefit'], 2);
        successCode($price);
    }
}